package com.leo.basic.utils;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @ClassName ReflectUtil
 * @Description
 * @Author wangss
 * @date 2021.09.23 17:54
 * @Version 1.0
 */

@Slf4j
public class ReflectUtil {

    public static void setFieldValue(Object object, String fieldName, Object value) {
        Field field = getDeclaredField(object, fieldName);
        if (null == field) {
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
        } else {
            makeAccessible(field);
            try {
                field.set(object, value);
            } catch (IllegalAccessException e) {
                log.error("通过反射设置属性值异常：{}", e.getMessage());
            }
        }
    }

    protected static Field getDeclaredField(Object object, String fieldName) {
        Class superClass = object.getClass();
        while (superClass != Object.class) {
            try {
                return superClass.getDeclaredField(fieldName);
            } catch (Exception e) {
                superClass = superClass.getSuperclass();
            }
        }
        return null;
    }

    protected static void makeAccessible(Field field) {
        if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
            field.setAccessible(true);
        }
    }
}
